package xxx.common.retrofit;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.springframework.context.annotation.Configuration;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.jaxb.JaxbConverterFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * @author yuanchengman
 * @date 2021-06-28
 */
@Configuration
public class JsonOrXmlConverterFactory extends Converter.Factory {
    private final Converter.Factory jsonFactory;
    private final Converter.Factory xmlFactory;

    public JsonOrXmlConverterFactory() {
        super();
        jsonFactory = GsonConverterFactory.create();
        xmlFactory = JaxbConverterFactory.create();
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        for (Annotation annotation : annotations) {
            if (annotation instanceof ResponseConverter) {
                if (((ResponseConverter) annotation).format().equals(ConverterFormat.JSON)) {
                    return jsonFactory.responseBodyConverter(type, annotations, retrofit);
                } else {
                    return xmlFactory.responseBodyConverter(type, annotations, retrofit);
                }
            }
        }
        return jsonFactory.responseBodyConverter(type, annotations, retrofit);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        for (Annotation annotation : methodAnnotations) {
            if (annotation instanceof RequestConverter) {
                if (((RequestConverter) annotation).format().equals(ConverterFormat.JSON)) {
                    return jsonFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
                } else {
                    return xmlFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
                }
            }
        }
        return jsonFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
    }

    @Override
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return super.stringConverter(type, annotations, retrofit);
    }
}
